//
//  EmoticonViewController.swift
//  测试键盘
//
//  Created by Tanenbaum on 15/8/6.
//  Copyright © 2015年 GZJ. All rights reserved.
//

import UIKit

let ZuoJEmoticonIdentifier = "ZuoJEmoticonIdentifier"
class EmoticonViewController: UIViewController {

    var selectedEmoticonCallBack: (emoticon:Emoticon) ->()
    
    init(selectedEmoticon:(emoticon:Emoticon) ->()) {
        
        
        selectedEmoticonCallBack  = selectedEmoticon
        super.init(nibName: nil, bundle: nil)
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //toolbar点击事件
    func ClickItem(item:UIBarButtonItem) {
        
        let indexPath = NSIndexPath(forItem: 0, inSection: item.tag)
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: true)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.lightGrayColor()
        setupUI()
        
    }
    
    override func viewDidAppear(animated: Bool) {
        
        super.viewDidAppear(animated)
        
        print(view)
    }
    
   //MARK --设置界面
    private func setupUI() {
     
         view.addSubview(collectionView)
         view.addSubview(toolbar)
        
         collectionView.translatesAutoresizingMaskIntoConstraints = false
         toolbar.translatesAutoresizingMaskIntoConstraints = false
        
         let dict = ["cv":collectionView,"tv": toolbar ]

         view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[cv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
         view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[tv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil , views: dict))
         view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[cv]-0-[tv(44)]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        
        prepareToolbar()
        prepareCollectionView()
        
    }
    
  
    // 设置toolbar
    private func prepareToolbar() {
        
        toolbar.tintColor = UIColor.orangeColor()
        var items = [UIBarButtonItem]()
        var index = 0
        for p in package {
            
            items.append(UIBarButtonItem(title: p.groupName, style: UIBarButtonItemStyle.Plain, target: self, action: "ClickItem:"))
            
            items.last?.tag = index++
            
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
           
        }
         items.removeLast()
        toolbar.items = items
    }
    
    //设置collectionView
    private func prepareCollectionView() {
        
        collectionView.registerClass(EmoticonViewCell.self, forCellWithReuseIdentifier: ZuoJEmoticonIdentifier)
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.pagingEnabled = true
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.bounces = false
    }
   
    //MARK --懒加载控件
    private lazy var toolbar: UIToolbar = UIToolbar()
    private lazy var package: [EmoticonPackage] = EmoticonPackage.package()
    private lazy var collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: ZuoJCollectionViewLayout())
    
    
    private class ZuoJCollectionViewLayout: UICollectionViewFlowLayout {
        
        private override func prepareLayout() {
            
            let s = (collectionView?.bounds.width)! / 7
            itemSize = CGSize(width: s, height: s)
            minimumInteritemSpacing = 0
            minimumLineSpacing = 0
            
            let marginY = ((collectionView?.bounds.height)! - 3 * s) * 0.499
            sectionInset = UIEdgeInsets(top: marginY, left: 0, bottom: marginY, right: 0)
            scrollDirection = UICollectionViewScrollDirection.Horizontal
        }
    }

    
}

//MARK -- 数据源方法
extension EmoticonViewController: UICollectionViewDataSource,UICollectionViewDelegate {
    
    
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
            let emoticon = package[indexPath.section].emoticons![indexPath.item]
           selectedEmoticonCallBack(emoticon: emoticon)
    }
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        
        return package.count
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return package[section].emoticons?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ZuoJEmoticonIdentifier, forIndexPath: indexPath) as! EmoticonViewCell
        
        cell.backgroundColor = indexPath.item % 2 == 0 ? UIColor.redColor() : UIColor.greenColor()
        cell.emoticon = package[indexPath.section].emoticons![indexPath.item]
        
        return cell
    }
    
}

//MARK --自定义cell
private class EmoticonViewCell: UICollectionViewCell {
    
    var emoticon: Emoticon? {
        didSet{
            
            emoticonButton.setImage(UIImage(contentsOfFile: emoticon!.imagePath), forState: UIControlState.Normal)
            emoticonButton.setTitle(emoticon!.emoji, forState: UIControlState.Normal)
            emoticonButton.titleLabel?.font  = UIFont.systemFontOfSize(32)
            
            if emoticon!.removeEmoticon {
                emoticonButton.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
                emoticonButton.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: UIControlState.Highlighted)
            }
           
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        emoticonButton.frame = CGRectInset(bounds, 4, 4)
        emoticonButton.backgroundColor = UIColor.whiteColor()
        emoticonButton.userInteractionEnabled = false
        contentView.addSubview(emoticonButton)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK -- 懒加载控件
    private lazy var emoticonButton: UIButton = UIButton()
}
